package com.ruoyi.core.config.mp;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.core.config.utils.WxUtil;
import com.ruoyi.core.config.vo.LoginVo;
import com.ruoyi.core.domain.vo.UserVo;
import com.ruoyi.core.service.IUserService;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;

/**
 * @作者：xie
 * @时间：2022/9/3 10:40
 */

@RestController
@RequestMapping("core/gzh")
@AllArgsConstructor
public class WxMpLoginController extends BaseController {
    private final WxMpService wxMpService;

    private final IUserService iUserService;
    @Anonymous
    @GetMapping("login")
    public R<LoginVo> login(@NotBlank(message = "code不为空") String code){

        //通过缓存判断用户信息
        UserVo userVo = WxUtil.getUserVoByToken();
        if(ObjectUtil.isNotNull(userVo)){
            WxUtil.refreshWxUser(userVo,false);
            return WxUtil.authMsg(userVo);
        }

        WxOAuth2UserInfo userinfo = getUserinfo(code);
        String openid = userinfo.getOpenid();
         userVo = iUserService.getByOpenid(openid);
        if (ObjectUtil.isNull(userVo)){
            UserVo userVo1 = iUserService.setWxUser(userinfo.getUnionId(), userinfo.getOpenid(), "0", userinfo.getNickname(), userinfo.getHeadImgUrl());
            return R.ok("登录成功",new LoginVo(StpUtil.getTokenValue(),userVo,"1"));
        }
        WxUtil.refreshWxUser(userVo,true);
            return R.ok("登录成功",new LoginVo(StpUtil.getTokenValue(),userVo,"0"));

    }

    private  WxOAuth2UserInfo getUserinfo(String code) {
        try {
            WxOAuth2AccessToken wxOAuth2AccessToken = wxMpService.getOAuth2Service().getAccessToken(code);
            WxOAuth2UserInfo userInfo = wxMpService.getOAuth2Service().getUserInfo(wxOAuth2AccessToken, null);
            System.out.println(userInfo.getNickname());
            System.out.println(userInfo.getHeadImgUrl());


            return userInfo;
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("getUser")
    public R<UserVo> getUser(){
        return R.ok(WxUtil.getUserVoByToken());
    }
}
